readNthLineInfile
Files Sandbox MaheP Mar21 Revised

Reading a Particular Line in a File

Problem
=======

Given a file name and the line number in the file - "n", return the nth line.

Solution
========

There are a number ways of solving this based on the usage. to accomplise this
using a function that takes a file name and the line number in the file, the
function would have to use the readline method of reading a file. A variable is
initialized before reading of the file and is incremented every time a line is
read. A check is done at every line to see if the line number is the one that
the function passed. The function is:

 function readNthLineInfile(filename, n)
 {
     current=0;
     line="";
     while ((getline < filename) > 0)
     {
         if (++current == n)
         {
             line = $ALL;
             break;
         }
     }
     close(filename);
     return line;
 }


The above methodology assumes that the file name is passed to the function which
would make the use of this function a likely candidate in the BEGIN or END
sections of the awk code. If, however the processing of the file is done in the
"main" body of the awk code, the build-in variables NR and FNR can be used to
query the line number being processed. Consider, the snippet of code:

  awk 'BEGIN { n=64; } { if (NR == n) { ... }}' f1.txt f2.txt ... f10.txt

In the above code, the awk code is passed ten files, ranging from f1.txt to
f10.txt. the variable NR keeps count of the number of lines read so far starting
with the first file. Hence, at the end the value of NR would the the total lines
of all the files combined. The snippet above will process the the 64th line being
processed. The snippet of code illustrating FNR is:

  awk 'BEGIN { n=64; } { if (FNR == n) { ... }}' f1.txt f2.txt ... f10.txt

The variable FNR tracks the line number of the current line being processed.
This means that every time the awk program starts reading a new file, the value
of FNR is reset. In the snippet above the code will process the 64th line in
each file (assuming that each file has atleast 64 lines).


Author
======

Mahesh Patel

